package cs4280.ass2.action;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang.time.DateUtils;

import cs4280.ass2.entity.Movie;
import cs4280.ass2.entity.ScheduleTO;
import cs4280.ass2.persistence.MovieDao;
import cs4280.ass2.persistence.ScheduleDao;
import cs4280.ass2.util.httpUtils;

public class TicketingAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<Movie> movieList = MovieDao.getInstance().retrieveAllMovie();
		Map<Long, List<ScheduleTO>> houseScheduleMap = new HashMap<Long, List<ScheduleTO>>();

		for (Movie movie : movieList) {
			List<ScheduleTO> scheduleList = ScheduleDao.getInstance().retrieveScheduleTOByMovie(movie.getId());
			if (!httpUtils.isLogined(req)) {
				scheduleList = (List<ScheduleTO>) CollectionUtils.select(
						scheduleList, new Predicate() {
							@Override
							public boolean evaluate(Object object) {
								ScheduleTO scheduleTO = (ScheduleTO) object;
								return DateUtils.isSameDay(new Date(),
										scheduleTO.getScheduleStart());
							}
						});
			}

			houseScheduleMap.put(movie.getId(), scheduleList);
		}

		req.setAttribute("movieList", movieList);
		req.setAttribute("houseScheduleMap", houseScheduleMap);
		getServletContext().getRequestDispatcher("/ticketing.jsp").forward(req, resp);
	}
}
